package com.his.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.his.dto.MedicineForPharmacy;
import com.his.dto.MedicineItemDetail;
import com.his.entity.*;
import com.his.mapper.DrugRefundItemRecordMapper;
import com.his.mapper.MedicineItemRecordMapper;
import com.his.mapper.MedicinePrescriptionRecordMapper;
import com.his.mapper.PharmacyMapper;
import com.his.service.IDrugRefundItemRecordService;
import com.his.service.IDrugService;
import com.his.service.IMedicineItemRecordService;
import com.his.service.IPharmacyService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

// 药房模块

@Service
public class PharmacyServiceImpl implements IPharmacyService {

    @Resource
    private PharmacyMapper mapper;

    @Resource
    private MedicinePrescriptionRecordMapper medicinePrescriptionRecordMapper;

    @Resource
    private IMedicineItemRecordService medicineItemRecordService;

    @Resource
    private IDrugService drugService;

    @Resource
    private DrugRefundItemRecordMapper drugRefundItemRecordMapper;

    @Resource
    private IDrugRefundItemRecordService refundItemRecordService;

    @Override
    public ResponseResult refresh() {
        Integer code = 0;
        String message = "";
        HashMap<String, Object> map = new HashMap<String, Object>();

        // prescription的status: 1 代表没发药 2 代表已发药
        try {
            map.put("distributed", mapper.getMedicineDistributed());
            map.put("undistributed", mapper.getMedicineUndistributed());

            code = 201;
            message = "拉取列表成功";
        } catch (Exception err) {
            code = 400;
            message = "拉取列表失败";
            map = null;
        }

        return new ResponseResult(code, message, map);
    }

    @Override
    public ResponseResult distributeMedicine(MedicinePrescriptionRecord medicinePrescriptionRecord) {
        Integer code = 0;
        String message = "";
        Collection<MedicineItemDetail> detailList = null;
        Collection<MedicineItemRecord> itemList = null;
        Collection<Drug> drugList = null;

        // prescription的status: 1 代表没发药 2 代表已发药
        try {
            detailList = mapper.getMedicineDetailListByPrescriptionId(medicinePrescriptionRecord.getId());


            if (null != detailList) {
                for (MedicineItemDetail e: detailList) {
                    Drug d = e.getDrug();
                    MedicineItemRecord i = e.getMedicineItemRecord();
                    d.setStock(d.getStock() - i.getNum());
                    i.setStatus(2);
                }
                drugList = detailList.stream().map(x -> x.getDrug()).collect(Collectors.toList());
                if (!drugService.updateBatchById(drugList)) {
                    throw new Exception();
                }
                itemList = detailList.stream().map(x -> x.getMedicineItemRecord()).collect(Collectors.toList());
                if (!medicineItemRecordService.updateBatchById(itemList)) {
                    throw new Exception();
                }
            } else {
                throw new Exception();
            }




            medicinePrescriptionRecord.setStatus(2);
            if (0 == medicinePrescriptionRecordMapper.updateById(medicinePrescriptionRecord)) {
                throw new Exception();
            }

            code = 201;
            message = "发药成功";
        } catch (Exception err) {
            code = 400;
            message = "发药失败";

        }

        return new ResponseResult(code, message, null);
    }

    @Override
    public ResponseResult returnMedicine(MedicinePrescriptionRecord medicinePrescriptionRecord) {
        Integer code = 0;
        String message = "";
        Collection<MedicineItemDetail> detailList = null;
        Collection<MedicineItemRecord> itemList = null;
        Collection<Drug> drugList = null;
        Collection<DrugRefundItemRecord> refundList = new ArrayList<DrugRefundItemRecord>();

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long staffId = loginUser.getUser().getId();

        // refundItem的id
        Long refundCount = 1L;
        // prescription的status: 1 代表没发药 2 代表已发药 3 退药
        try {
            detailList = mapper.getMedicineDetailListByPrescriptionId(medicinePrescriptionRecord.getId());
            medicinePrescriptionRecord = medicinePrescriptionRecordMapper.selectOne(new QueryWrapper<MedicinePrescriptionRecord>().eq("id", medicinePrescriptionRecord.getId()));

            refundCount = drugRefundItemRecordMapper.getMaxId();
            if (null == refundCount)
                refundCount = 0L;

            if (null != detailList) {
                for (MedicineItemDetail e: detailList) {
                    Drug d = e.getDrug();
                    MedicineItemRecord i = e.getMedicineItemRecord();
                    d.setStock(d.getStock() + i.getNum());
                    i.setStatus(3);

                    //增加退药单
                    DrugRefundItemRecord refundItem = new DrugRefundItemRecord();
                    refundItem.setId(++refundCount);
                    refundItem.setDrugid(i.getDrugid());
                    refundItem.setStatus(1);
                    refundItem.setRefunditemrecordid(i.getId());
                    refundItem.setRegistrationid(medicinePrescriptionRecord.getRegistrationid());
                    refundItem.setRefundtime(LocalDateTime.now());
                    refundItem.setExcutorid(staffId);
                    refundItem.setStatus(1);
                    refundItem.setType(0);
                    refundList.add(refundItem);
                }
                drugList = detailList.stream().map(x -> x.getDrug()).collect(Collectors.toList());
                if (!drugService.updateBatchById(drugList)) {
                    throw new Exception();
                }
                itemList = detailList.stream().map(x -> x.getMedicineItemRecord()).collect(Collectors.toList());
                if (!medicineItemRecordService.updateBatchById(itemList)) {
                    throw new Exception();
                }
            } else {
                throw new Exception();
            }

            if (!refundItemRecordService.saveBatch(refundList)) {
                throw new Exception();
            }

            medicinePrescriptionRecord.setStatus(3);
            if (0 == medicinePrescriptionRecordMapper.updateById(medicinePrescriptionRecord)) {
                throw new Exception();
            }

            code = 201;
            message = "发药成功";
        } catch (Exception err) {
            code = 400;
            message = "发药失败";

        }

        return new ResponseResult(code, message, null);
    }
}
